package club.gggd.security_jwt_demo.util;

import club.gggd.security_jwt_demo.pojo.entity.SysUser;
import club.gggd.security_jwt_demo.pojo.module.JwtUser;
import club.gggd.security_jwt_demo.pojo.module.TokenConstant;
import club.gggd.security_jwt_demo.pojo.module.TokenInfo;
import club.gggd.security_jwt_demo.pojo.module.TokenSign;
import club.gggd.security_jwt_demo.service.UserService;
import club.gggd.security_jwt_demo.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description 用户提供者
 * @Author srx
 * @date 2023/12/9 15:47
 */
@Component
public class UserProvider {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取当前用户信息
     * @return
     */
    public JwtUser curUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
        return jwtUser;
    }

    /**
     * 获取用户id
     * @return
     */
    public Integer getUserId() {
        return curUser().getId();
    }

    /**
     * 获取用户账号
     * @return
     */
    public String getAccount() {
        return curUser().getAccount();
    }

    /**
     * 踢出该账号的所有登录信息
     * @param account
     */
    public void kickOutUserByAccount(String account) {
        // 拿到session信息
        TokenInfo sessionInfo = (TokenInfo) redisUtil.get(TokenConstant.SESSION + account);
        if (sessionInfo != null) {
            List<TokenSign> tokenSignList = sessionInfo.getTokenSignList();
            // 删除全部token
            for (TokenSign t : tokenSignList) {
                redisUtil.del(TokenConstant.TOKEN + t.getToken());
            }
            // 删除session里的token
            tokenSignList.clear();
            redisUtil.set(TokenConstant.SESSION + account, sessionInfo);
        }
    }

    /**
     * 踢出该token的登录信息
     * @param token
     */
    public void kickOutUserByToken(String token) {
        // 拿到账号
        String account = (String) redisUtil.get(TokenConstant.TOKEN + token);
        // 拿到session
        TokenInfo sessionInfo = (TokenInfo) redisUtil.get(TokenConstant.SESSION + account);
        List<TokenSign> tokenSignList = sessionInfo.getTokenSignList();
        // 删除session中的token
        tokenSignList.removeIf(e -> e.getToken().equals(token));
        // 删除token
        redisUtil.del(TokenConstant.TOKEN + token);
        redisUtil.set(TokenConstant.SESSION + account, sessionInfo);
    }
}
